package com.bst.base.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.sql.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.bst.base.vo.BaseNoteParamVO;
import com.bst.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.bst.base.mapper.BaseNoteMapper;
import com.bst.base.domain.BaseNote;
import com.bst.base.service.IBaseNoteService;
import com.bst.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * 系统通知Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-11-15
 */
@Service
public class BaseNoteServiceImpl implements IBaseNoteService 
{
    @Autowired
    private BaseNoteMapper baseNoteMapper;

    /**
     * 查询系统通知
     * 
     * @param idNote 系统通知主键
     * @return 系统通知
     */
    @Override
    public BaseNote selectBaseNoteByIdNote(Long idNote)
    {
        return baseNoteMapper.selectBaseNoteByIdNote(idNote);
    }

    /**
     * 查询系统通知列表
     * 
     * @param baseNote 系统通知
     * @return 系统通知
     */
    @Override
    public List<BaseNote> selectBaseNoteList(BaseNoteParamVO baseNote)
    {
        return baseNoteMapper.selectBaseNoteList(baseNote);
    }

    /**
     * 新增系统通知
     * 
     * @param baseNote 系统通知
     * @return 结果
     */
    @Override
    public int insertBaseNote(BaseNote baseNote)
    {
        return baseNoteMapper.insertBaseNote(baseNote);
    }

    /**
     * 修改系统通知
     * 
     * @param baseNote 系统通知
     * @return 结果
     */
    @Override
    public int updateBaseNote(BaseNote baseNote)
    {
        return baseNoteMapper.updateBaseNote(baseNote);
    }

    @Override
    public int updateBatchBaseNote(List<BaseNote> notes) {
        return baseNoteMapper.updateBatchBaseNote(notes);
    }

    /**
     * 批量删除系统通知
     * 
     * @param idNotes 需要删除的系统通知主键
     * @return 结果
     */
    @Override
    public int deleteBaseNoteByIdNotes(String idNotes)
    {
        return baseNoteMapper.deleteBaseNoteByIdNotes(Convert.toStrArray(idNotes));
    }

    /**
     * 删除系统通知信息
     * 
     * @param idNote 系统通知主键
     * @return 结果
     */
    @Override
    public int deleteBaseNoteByIdNote(Long idNote)
    {
        return baseNoteMapper.deleteBaseNoteByIdNote(idNote);
    }

    /**
     *
     * @param notes
     */
    @Override
    @Transactional
    public void insertBatchBaseNote(List<BaseNote> notes) {
        baseNoteMapper.insertBatchBaseNote(notes);
        //取消即时信息发送
        /*List<String> fks = new ArrayList<>();
        for (BaseNote note : notes) {
            if(!fks.contains(note.getField1())) {
                fks.add(note.getField1());
            }
        }
        String sdCNoteSour = notes.get(0).getSdNoteSour();
        notes = baseNoteMapper.selectMustSendNoteByField1(sdCNoteSour,fks,new java.util.Date());
        if(notes.size()>0) {
            sendMsg(notes);
            List<Long> ids = new ArrayList<>();
            for (BaseNote note : notes) {
                ids.add(note.getIdNote());
            }
            baseNoteMapper.updateStatusByIds(1,ids);
        }*/
    }

    @Override
    public int updateStatusByIds(Integer euNote, List<Long> list) {
        return baseNoteMapper.updateStatusByIds(euNote,list);
    }

    @Override
    public int updateCancelForInvalidPati() {
        return baseNoteMapper.updateCancelForInvalidPati();
    }

    @Resource(name = "noteDataSource")
    DataSource noteDataSource;

    @Transactional
    public void sendMsg2(List<BaseNote> noteList) {
        String address = "http://172.16.0.182/sms10000/api/send?userId=Zbglxtdxjk&pwd=Szlgzyy1021";// &mobile=手机号&content=发送内容";
        String newAddress;
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        JSONObject jsonObject;String result;
        HttpURLConnection connection=null;
        for (BaseNote note : noteList) {
            newAddress = address+"&mobile="+note.getTel()+"&content="+note.getDes();
            try {
                URL url = new URL(newAddress);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();
                InputStream is = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String strRead = null;
                sbf = new StringBuffer();
                while ((strRead = reader.readLine()) != null) {
                    sbf.append(strRead);
                }
                if(StringUtils.isNotEmpty(sbf.toString())) {
                    jsonObject = JSONObject.parseObject(sbf.toString());
                    result = jsonObject.getString("tips");
                    if(StringUtils.isNotEmpty(result)) {
                        note.setDesSend(result.length()>100?result.substring(0,100):result);
                    }
                    note.setFgSend(Integer.parseInt(jsonObject.getString("result")));
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                note.setDtNote(new java.util.Date());
                note.setEuNote(1L);
                try {
                    if(reader!=null) {
                        reader.close();
                        connection.disconnect();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 短信发送(历史问题已作废，稍后删除)
      */
    @Transactional
    public void sendMsg(List<BaseNote> noteList) {
        String sql = "insert into OA_t_SendSMS(FSender,FReceiver,FContent,FType,FState,FCheck,FExt1,FReceiverName,FOperName,FCreateTime,FCreateUser) " +
                "values(?,?,?,?,?,?,?,?,?,?,?);";
        JdbcTemplate template = new JdbcTemplate(noteDataSource);
        template.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                BaseNote note = noteList.get(i);
                ps.setString(1, "MG");
                ps.setString(2, note.getTel());
                ps.setString(3, note.getDes());
                ps.setString(4,"短信");
                ps.setInt(5, 0);
                ps.setInt(6, 1);
                ps.setString(7,"慢病");
                ps.setString(8, note.getNaEmp());
                ps.setString(9, note.getNaEmpCre());
                ps.setDate(10, new Date(new java.util.Date().getTime()));
                ps.setString(11, note.getNaEmpCre());
            }
            @Override
            public int getBatchSize() {
                return noteList.size();
            }
        });
    }
}
